#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Common.h"
#include "Window.h"
#include "Internals.h"

#include "Timer.h"


typedef struct _timer {
    HWND    hWnd;
    int     id;
    int     softimer_id;
} TIMER;
typedef TIMER* PTIMER;

static TIMER *timerstr[DEF_NR_TIMERS];

BOOL GUIAPI SetTimer (HWND hWnd, int id, unsigned int speed)
{
    int i;
    int slot = -1;

    /* Is there an empty timer slot? */
    for (i=0; i<DEF_NR_TIMERS; i++) 
    {
        if (timerstr[i] == NULL) 
        {
            if (slot < 0)
                slot = i;
        }
        else if (timerstr[i]->hWnd == hWnd && timerstr[i]->id == id) 
        {
            goto badret;
        }
    }

    if (slot < 0 || slot == DEF_NR_TIMERS)
        goto badret ;

    timerstr[slot] = malloc (sizeof (TIMER));

    timerstr[slot]->hWnd = hWnd;
    timerstr[slot]->id = id;

    i = msTimerStart(MSTIMER__HANDLE_TIMEOUT, speed, NULL, hWnd);

    if(i != -1)
    {
        timerstr[slot]->softimer_id = i;
    }
    else
    {
        goto badret;
    }

    return TRUE;

badret:
    return FALSE;
}

/* If id <= 0, clear all timers of the window */
int GUIAPI KillTimer (HWND hWnd, int id)
{
    int i;
    int killed = 0;

    for (i = 0; i < DEF_NR_TIMERS; i++) 
    {
        if ((timerstr [i] && timerstr [i]->hWnd == hWnd) &&
                        (id <= 0 || timerstr [i]->id == id)) 
        {                 
            msTimerStop (timerstr [i]->id);
            free (timerstr[i]);
            timerstr [i] = NULL;
            killed ++;

            if (id > 0) break;
        }
    }

    return killed;
}
